package com.vm.myview;

import java.io.File;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.StringRequest;
import com.vm.broadcast.AppInstallReceiver;
import com.vm.commons.CurrentSetting;
import com.vm.commons.CurrentUser;
import com.vm.commons.ProgressUtil;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.vm.db.DownInfoDao;
import com.vm.db.OperationDao;
import com.vm.model.ActiveSoft;
import com.vm.model.DownInfo;
import com.vm.model.Soft;
import com.vm.utils.ApkUtils;
import com.vm.utils.ButtonStyle;
import com.vm.utils.ConnectManager;
import com.vm.utils.DownloadThread;
import com.vm.utils.MyVolley;
import com.vm.utils.SoftDataUtil;
import com.wwtscapp.apk.R;

@SuppressLint("ShowToast")
public class GridViewDown {

	private DownloadThread downThread;
	private Handler downHandler;
	private Context mContext;
	LinearLayout layout;
	Button btn_download;
	// RelativeLayout rlayout_progressBar;
	View view;
	DownInfoDao dao;
	DownInfo apkInfo;
	private int nowProgressValue = 0;
	ActiveSoft activeSoft;
	TextView tv_download_num;
	ButtonStyle buttonStyle;

	public GridViewDown(Context context, View view, ActiveSoft activeSoft) {

		this.mContext = context;
		this.view = view;
		dao = new DownInfoDao(context);
		this.activeSoft = activeSoft;
		// timer = new Timer(true);
		// timer.schedule(task, 1000, 10000); // 延时1000ms后执行，1000ms执行一次
		initProgressBar();
		downThread = new DownloadThread(mContext, mainHandler);
	}

	public void initProgressBar() {

		init();
		boolean isInstalled = ApkUtils.isAppInstalled(
				activeSoft.getPackageName(), mContext);
		// 判断APK是否有安装
		if (isInstalled) {
			btn_download.setText("已安装");
			buttonStyle.setBtnStyle(4);
			btn_download.setEnabled(false);
		} else {

			File apkfile = new File(
					StringUtil.getSdApkUrl(activeSoft.getName()));
			if (apkfile.exists()) {

				// 判断APK在机器的状态,正在下载,已下载,已安装
				apkInfo = dao.query(activeSoft.getSoftId());
				if (apkInfo != null) {
					if (apkInfo.getCompleted() == null
							|| apkInfo.getCompleted() == 0) {

						if (apkInfo.getIsPause() == 0) {
							// rlayout_info.setVisibility(View.GONE);
							// progressBar.setVisibility(View.VISIBLE);
							//
							// // currentId = v.getTag().toString();
							// // Log.i(TAG, currentId);
							// // System.out
							// // .println("<<<<" + nowProgressValue + "<<<" +
							// // fileSize);
							// // progressText.setText("稍等");
							// // progressText.setTextColor(Color.BLACK);
							// Message msg = new Message();
							// // msg.arg1 = currentId;
							// msg.what = 100;
							// // 下载地址
							// // msg.obj = VMConst.DOWN_URL + currentId +
							// // "&userId="
							// // + CurrentUser.USERID;
							// Soft soft = new Soft();
							// soft.setId(activeSoft.getSoftId());
							// soft.setImageUrl(activeSoft.getImageUrl());
							// soft.setApkUrl(activeSoft.getApkUrl());
							// soft.setName(activeSoft.getName());
							// msg.obj = soft;
							//
							// dao.start(activeSoft.getSoftId());
							// //
							// // downThread = new DownloadThread(mContext,
							// // mainHandler);
							// downThread.start();
							//
							// ProgressUtil.hashMap.put(activeSoft.getSoftId(),
							// nowProgressValue);
							//
							// do {
							// downHandler = downThread.getDownHandler();
							// } while (null == downHandler);
							//
							// downHandler.sendMessage(msg);
							btn_download.setText("暂停");
							buttonStyle.setBtnStyle(1);
						} else {
							// downThread.isPause = true;
							btn_download.setText("继续");
							buttonStyle.setBtnStyle(1);
						}
					} else {
						btn_download.setText("安装");
						buttonStyle.setBtnStyle(3);
					}
				}
			}
		}
	}

	/**
	 * 初始化控件
	 */
	private void init() {
		tv_download_num = (TextView) view.findViewById(R.id.tv_download_num);
		btn_download = (Button) view.findViewById(R.id.btn_download);
		buttonStyle = new ButtonStyle(mContext, btn_download);
		btn_download.setOnClickListener(downClickListener);

		// rlayout_progressBar = (RelativeLayout) view
		// .findViewById(R.id.rlayout_progressBar);

	}

	@SuppressLint("HandlerLeak")
	private Handler mainHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 100:
				btn_download.setText("已安装");
				buttonStyle.setBtnStyle(4);
				// 发送增加记录到数据库执行增加下载记录

				// // String code = TelephonyManager.d
				// String softName = activeSoft.getName();
				// try {
				// softName = URLEncoder.encode(softName, "UTF-8");
				// } catch (UnsupportedEncodingException e) {
				// // TODO Auto-generated catch block
				// e.printStackTrace();
				// }
				// String url = VMConst.REQUEST_URL + "addDownRecord?softId="
				// + activeSoft.getSoftId() + "&softName=" + softName
				// + "&userId=" + CurrentUser.USERID + "&deviceId="
				// + StringUtil.DEVICEID;
				//
				// StringRequest stringRequest = new StringRequest(url,
				// new Listener<String>() {
				//
				// @Override
				// public void onResponse(String arg0) {
				// // TODO Auto-generated method stub
				//
				// }
				// }, null);
				// RequestQueue mQueue = MyVolley.getRequestQueue();
				// mQueue.add(stringRequest);
				if (CurrentSetting.autodelete == 1) {
					File apkfile = new File(Environment
							.getExternalStorageDirectory().getPath()
							+ "/vmclient/" + activeSoft.getName() + ".apk");
					if (apkfile.exists()) {
						apkfile.delete();
					}
				}
				addRecord();
				break;
			case 200:
				break;

			// case 500:
			// if (nowProgressValue <= fileSize) {
			//
			// fileSize = msg.arg1;
			// progressBar.setMax(fileSize);
			// new Thread() {
			// @Override
			// public void run() {
			// while (true) {
			// progressBar.setProgress(nowProgressValue);
			// }
			// }
			// }.start();
			// // }
			// } else {
			// Toast toast = Toast.makeText(mContext, "当前附件已下载", 500);
			// toast.setGravity(Gravity.CENTER, 0, 0);
			// toast.show();
			// }
			//
			// break;
			case 600:
				nowProgressValue = msg.arg1;
				ProgressUtil.hashMap.put(activeSoft.getSoftId(),
						nowProgressValue);
				break;
			case 700:
				Toast toast = Toast.makeText(mContext, "网络异常或当前附件不存在", 500);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				break;
			case 800:
				Toast toast1 = Toast.makeText(mContext, "URL异常，请联系管理员", 500);
				toast1.setGravity(Gravity.CENTER, 0, 0);
				toast1.show();
				break;
			case 900:
				Toast toast2 = Toast.makeText(mContext, "暂停下载", 500);
				toast2.setGravity(Gravity.CENTER, 0, 0);
				toast2.show();
				break;
			case 1000:
				Toast toast3 = Toast.makeText(mContext, "下载完成", 500);
				toast3.setGravity(Gravity.CENTER, 0, 0);
				toast3.show();
				btn_download.setText("安装");
				buttonStyle.setBtnStyle(3);
				dao.complete(activeSoft.getSoftId());
				File apkfile = new File(StringUtil.getSdApkUrl(activeSoft
						.getName()));
				if (!apkfile.exists()) {
					return;
				}

				AppInstallReceiver.mainHandler = mainHandler;
				if (CurrentSetting.autoinstall == 1) {
					Intent i = new Intent(Intent.ACTION_VIEW);

					i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
							"application/vnd.android.package-archive");
					view.getContext().startActivity(i);
					OperationDao op = new OperationDao();
					if (op.query(activeSoft.getPackageName()) == 1) {

					} else {
						op.insert(activeSoft.getId(),
								activeSoft.getPackageName());
					}
				}
				new NotificationView(view.getContext(),
						activeSoft.getImageUrl(),
						activeSoft.getName() + "下载完成", "点击安装", "下载完成",
						apkfile.toString());
				if (CurrentSetting.zeroflow == 1) {
					SoundPool pool = new SoundPool(10,
							AudioManager.STREAM_MUSIC, 5);
					// 载入音频流，返回在池中的id
					final int sourceid = pool.load(mContext, R.raw.down, 0);
					pool.setOnLoadCompleteListener(new OnLoadCompleteListener() {

						@Override
						public void onLoadComplete(SoundPool soundPool,
								int sampleId, int status) {
							// TODO Auto-generated method stub
							soundPool.play(sourceid, 2, 2, 0, 0, 1);
						}

					});
				}
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};
	@SuppressLint("HandlerLeak")
	private Handler downloadHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 10:
				if (btn_download.getText().toString().equals("下载")) {
					btn_download.setText("暂停");
					buttonStyle.setBtnStyle(1);
					Message msg1 = new Message();
					msg1.what = 100;
					Soft soft = new Soft();
					soft.setId(activeSoft.getSoftId());
					soft.setImageUrl(activeSoft.getImageUrl());
					soft.setApkUrl(activeSoft.getApkUrl());
					soft.setName(activeSoft.getName());
					msg1.obj = soft;
					downThread.start();
					ProgressUtil.hashMap.put(activeSoft.getSoftId(),
							nowProgressValue);
					do {
						downHandler = downThread.getDownHandler();
					} while (null == downHandler);
					Toast toast = Toast.makeText(view.getContext(), "下载文件",
							500);
					toast.show();
					downHandler.sendMessage(msg1);

				} else if (btn_download.getText().toString().equals("继续")) {
					Message msg1 = new Message();
					// msg.arg1 = currentId;
					msg1.what = 100;
					// 下载地址
					// msg.obj = VMConst.DOWN_URL + currentId + "&userId="
					// + CurrentUser.USERID;
					Soft soft = new Soft();
					soft.setId(activeSoft.getSoftId());
					soft.setImageUrl(activeSoft.getImageUrl());
					soft.setApkUrl(activeSoft.getApkUrl());
					soft.setName(activeSoft.getName());
					msg1.obj = soft;

					dao.start(activeSoft.getSoftId());
					//
					downThread = new DownloadThread(mContext, mainHandler);
					downThread.start();

					ProgressUtil.hashMap.put(activeSoft.getSoftId(),
							nowProgressValue);

					do {
						downHandler = downThread.getDownHandler();
					} while (null == downHandler);

					downHandler.sendMessage(msg1);
					btn_download.setText("暂停");
					buttonStyle.setBtnStyle(1);
				}
				break;
			}
		}
	};
	/**
	 * 下载按钮监听
	 */
	public OnClickListener downClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			initProgressBar();
			if (btn_download.getText().toString().equals("安装")) {
				// 执行安装
				Toast toast3 = Toast.makeText(mContext, "正在安装", 500);
				toast3.setGravity(Gravity.CENTER, 0, 0);
				toast3.show();

				File apkfile = new File(StringUtil.getSdApkUrl(activeSoft
						.getName()));
				if (!apkfile.exists()) {
					return;
				}
				Intent i = new Intent(Intent.ACTION_VIEW);
				i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
						"application/vnd.android.package-archive");
				view.getContext().startActivity(i);
				OperationDao op = new OperationDao();
				if (op.query(activeSoft.getPackageName()) == 1) {

				} else {
					op.insert(activeSoft.getId(), activeSoft.getPackageName());
				}
				AppInstallReceiver.mainHandler = mainHandler;
			} else if (btn_download.getText().toString().equals("暂停")) {
				// downThread = new DownloadThread(mContext, mainHandler);

				// ProgressUtil.hashMap.put(activeSoft.getSoftId(),
				// nowProgressValue);
				//
				// do {
				// downHandler = downThread.getDownHandler();
				// } while (null == downHandler);

				// downHandler = downThread.getDownHandler();
				downThread.isPause = true;
				btn_download.setText("继续");
				buttonStyle.setBtnStyle(1);
				dao.stop(activeSoft.getSoftId());
				// int a = apkInfo.getIsPause();
			} else {
				ConnectManager.isDownload(mContext);
				ConnectManager.mainHandler=downloadHandler;
			}
		}
	};

	/**
	 * 上传下载记录
	 */
	public void addRecord() {
		if (CurrentUser.USERID != null) {
			RequestQueue mQueue = MyVolley.getRequestQueue();

			String url = VMConst.REQUEST_URL + "addDownloadRecord?userId="
					+ CurrentUser.USERID + "&softId=" + activeSoft.getSoftId()
					+ "&deviceId=" + StringUtil.DEVICEID;

			StringRequest ifGetRequest = new StringRequest(url,
					new Listener<String>() {

						@Override
						public void onResponse(String response) {
							if (response.contains("成功")) {
								System.out.println("success");
								if (activeSoft.getDownload() != null) {
									int download1 = activeSoft.getDownload() + 1;
									String download = SoftDataUtil.getSoftDownload(download1);
									tv_download_num.setText(download);
								}
							}
						}
					}, new ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
						}
					});
			mQueue.add(ifGetRequest);
		}
	}
}


